# coding:utf-8
from slb_aliyun import SLBmanage
from slb_jenkins import jenkins_svn
from datetime import datetime

class main_body(object):
    def __init__(self, ansible_v):
        self.jenkins_class = jenkins_svn()
        self.aliyun_class = SLBmanage()
        self.ansible_v = ansible_v

    def cycle_build(self, slb_data):
        slb_list = slb_data["slb_list"]
        j_server = self.jenkins_class.start_jk()
        build_status = 0
        for item in slb_list:
            build_data = self.jenkins_class.job_build(item["jenkins_name"], j_server)
            if build_data["status"]:
                item["build_status"] = True
                item["end_build_id"] = build_data["end_build_id"]
                item["msg_data"] = build_data["msg_data"]
            else:
                build_status += 1
                item["build_status"] = False
                item["end_status"] = 1 #代表jenkins build失败
        j_server.close()
        if build_status == 0:
            self.cycle_remove(slb_data)
            return slb_data
        else:
            return slb_data

    #根据定义好的playbook进行文件发送
    def cycle_send(self, rapi, item, yml_file):
        return_status = {"status": False}
        date = datetime.now().strftime("%Y%m%d")
        if self.ansible_v == "2.3":
            return_status = {"status": False}
            date = datetime.now().strftime("%Y%m%d")
            r_data, b_data = rapi.get_result()
            if b_data["success"] != {}:
                return_status["status"] = True
        elif self.ansible_v == "2.4":
            ret = rapi.run(yml_file,
                           {'host': item["group_name"], 'user': 'root', 'datetime': date, 'webname': item["war_name"]})
            status_data = ret["status"]
            perform_status = False
            for v in status_data.values():
                if v["failures"] == 0 and v["unreachable"] == 0 and v["skipped"] == 0:
                    perform_status = True
                else:
                    perform_status = False
            if perform_status:
                print("更新成功！")
            return_status["status"] = perform_status
        return return_status

    #
    def cycle_remove(self, slb_data):
        a_server = self.aliyun_class.start_clt()
        if self.ansible_v == "2.3":
            from ansible_2_3.ansibleapi import MyRunner
            rapi = MyRunner(slb_data["ansible_group"])
        elif self.ansible_v == "2.4":
            from  ansible_2_4.runner import RuleRunner, PlayBookRunner, CommandRunner
            from  ansible_2_4.inventory import BaseInventory
            inventory = BaseInventory(slb_data["ansible_group"])
            rapi = PlayBookRunner(inventory)

        slb_list = slb_data["slb_list"]
        for item in slb_list:
            re_BackendServers = [{"ServerId": item["ServerId"]}]
            remove_data = self.aliyun_class.removeBack(item["BalancerId"], re_BackendServers, a_server)
            if remove_data["status"]:
                ab_data = self.cycle_send(rapi, item, slb_data["yml_file"])
                if ab_data["status"]:
                    ad_BackendServers = [{"ServerId":item["ServerId"], "Weight":item["Weight"]}]
                    add_data = self.aliyun_class.addBack(item["BalancerId"], ad_BackendServers, item["request_url"], a_server)
                    if add_data["status"] != 0:
                        item["end_status"] = add_data["status"]
                        return
                    else:
                        item["end_status"] = add_data["status"]
                        print("更新成功！")
                else:
                    item["end_status"] = 3 # 代表发送或解压失败失败
                    return
            else:
                item["end_status"] = 2 #代表移除失败
                return

if __name__ == "__main__":
    data = {"slb_list":[{"BalancerId":"lb-xxxx", "ServerId":"i-xxxx","jenkins_name":"线上WEB2","war_name":"secuxxxxxx.zip", "request_url":"http://xxxx/web/cloudManage/getPeopleCountsByPhone.json", "group_name":"web2", "Weight":100}], "yml_file":"/opt/playbook/slb_web.yml", "ansible_group":{"web2": {"hosts": [{'username': 'root','hostname': 'xxxxx','ip': 'xxxxxx'}]}}}
    a  = main_body("2.4")
    a.cycle_build(data)